<?php

namespace App\Library\Logic;

use App\Library\Requests\Base\BasePageRequest;
use App\Models\ShopUserMessageModel;
use Illuminate\Http\JsonResponse;

class ShopUserMessageLogic extends ShopUserMessageModel
{
    /**
     * 分页
     * @param BasePageRequest $request
     * @return array
     */
    public function paging(BasePageRequest $request): array
    {
        return paginate($this->newQuery()->leftJoin('shop_user', 'shop_user.user_id', 'shop_user_message.um_send_user_id')
            ->where('shop_user_message.um_receive_user_id', USERID)
            ->orderByDesc('shop_user_message.um_status')
            ->orderByDesc('shop_user_message.im_add_time')
            ->orderByDesc('shop_user_message.um_id')->paginate($request->limit, [
                'um_id',
                'um_type',
                'um_status',
                'um_send_user_id as acceptId',
                'im_add_time',
                'um_content',
                'shop_user.user_mobile',
                'shop_user.user_nickname',
                'shop_user.user_avatar'
            ]));
    }

    /**
     * 客服消息 - 添加
     * @param int $userId
     * @param int $acceptId
     * @param string $content
     * @return void
     */
    public static function add(int $userId, int $acceptId, string $content): void
    {
        $where = ['umType' => 4, 'userId' => $userId, 'umReceiveUserId' => $acceptId];
        $model = ShopUserMessageLogic::findByWhere($where, null, 'um_id');
        $status = $acceptId === USERID ? 1 : 2;
        if (!is_null($model)) {
            $model->im_add_time = time();
            $model->um_content = $content;
            $model->um_status = $status;
            $model->save();
        } else {
            ShopUserMessageLogic::insertForModel(array_merge($where, [
                'umSendUserId' => $userId,
                'umContent' => $content,
                'imAddTime' => time(),
                'umStatus' => $status,
            ]));
        }
    }
}
